<?php
namespace Admin\Model;
class MenuModel extends AdminBaseModel
{
    protected $tableName = 'menu';

    /**菜单排序显示，二级菜单
     *
     * @param $separate 分隔符
     * @param $ignoreRole 是否忽略角色 是 则显示所有的菜单 否 则显示拥有的权限的菜单
     */
    public function treeList($separate = '',$ignoreRole = false)
    {
        $where['status'] = 1;
        $where['pid'] = 0;
        if (C('DEVELOP_MODE') != 'dev') {
            $where['is_dev'] = 0;
        }
        //获取用户所拥有的权限 超级管理员不受权限限制
        $userInfo = $this->loginInfo;
        if($userInfo['role_id'] == 1 || $ignoreRole){
            $ownRule =  M('admin_rule')->where('status = 1')->getField('url',true);
        }else{
            $ownRule = M('admin_role_rule')->alias('arr')
                ->join('rj_admin_rule ar on arr.rule_id = ar.id')
                ->where("arr.role_id = {$userInfo['role_id']} and status = 1")->getField('url',true);
        }

        $list = $this->field('id,title,pid,sort,url')->where($where)->order('sort desc')->select();
        $menuList = [];
        foreach ($list as $k => $v) {
            $menuList[$k] = $v;
            $where['pid'] = $v['id'];
            $tempList = $this->field('id,title,pid,sort,url')->where($where)->order('sort desc')->select();
            foreach ($tempList as $k2 => $v2) {
                if(in_array($v2['url'],$ownRule)){
                    $v2['title'] = $separate . $v2['title'];
                    $menuList[$k]['sub'][] = $v2;
                }
            }
        }
        if(!$ignoreRole){
            foreach($menuList as $k =>$v){
                if(empty($v['sub'])){
                    unset($menuList[$k]);
                }
            }
        }
        return $menuList;
    }

    public function getMaxSort()
    {
        return $this->max('sort');
    }
}